import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { BasePage } from '../base/BasePage';
import { ResManager } from './ResManager';
import { IPageInfo, PageConfig } from '../comm/PageConfig';
const { ccclass, property } = _decorator;

@ccclass('PageManager')
class PageManager {
    private _pages: BasePage[];
    private _low: Node; // Page层
    private _mid: Node; // Dialog层
    private _high: Node; // Toast、全局遮罩
    public init(low: Node, mid: Node, high: Node) {
        this._low = low;
        this._mid = mid;
        this._high = high;
        // 用Proxy监听_pages的操作
        this._pages = new Proxy([], {
            get(target: any, prop: string, receiver: any) {
              if (prop === 'push') {
                return function(...args: any[]) {
                  console.log(`Adding items: ${args}`);
                  return target.push.apply(target, args);
                };
              } else if (prop === 'pop') {
                return function() {
                  console.log('Removing last item');
                  return target.pop.apply(target, arguments);
                };
              } else if (prop === 'splice') {
                return function(start: number, deleteCount: number, ...items: any[]) {
                  console.log(`Splicing at index ${start}, deleting ${deleteCount} items, adding ${items}`);
                  return target.splice.apply(target, arguments);
                };
              }
              return Reflect.get(target, prop, receiver);
            }
        })
        
    }
    
    public async push(pageInfo: string): Promise<void>;
    public async push(pageInfo: IPageInfo): Promise<void>;
    public async push(pageInfo: string | IPageInfo) {
        if (typeof pageInfo === 'string') {
            pageInfo = PageConfig[pageInfo] as IPageInfo;
        }
        let prefab = await ResManager.load('res', pageInfo.path, Prefab);
        let node = instantiate(prefab);
        node.parent = this._low;
        const page = <BasePage>node.getComponent(pageInfo.class);
        this._pages.push(page);
    }
}


export default new PageManager();